import { getKonwLedge,getKnowPid } from '@/services';

const state = {
  knowlist: null, //知识小册的数据
  DetailPList: [],//第一个详情的数据
  DetailKList:[],//第二个详情的数据
  DetailHeight:0
};

const mutations = {
  KnowLedge(state, data) {
    state.knowlist = data;
  },
  updated(state, payload) {
    for (let key in payload) {
      // console.log(key);
      state[key] = payload[key]
    }
  },
  KnowledgeLikes(state,payload){
    // console.log(payload);  //详情页的id
    // console.log(state.DetailKList);
    if(state.DetailKList.id==payload){
      state.DetailKList.likes=!state.DetailKList.likes;
      state.DetailKList.likes>0?state.DetailKList.likes=+1:state.DetailKList.likes=0;
    }
  },
  KnowledgeHeight(state, data){
    state.DetailHeight = data*1+140
  }
};

const actions = {
  // 请求所有的知识小册的数据
  async getKnowLedge({ commit }) {
    let res = await getKonwLedge();
    commit("KnowLedge", res[0]);
  },
  // 异步请求知识小册详情的数据
  async getDetail({ commit },payload) {
    let result = await getKnowPid(payload);
    // console.log(result, "-----------------------------------");
    // if(result){
    //   let DetailPList=result
    //   console.log(DetailPList)
    //   commit("updated",{DetailPList:DetailPList})
    // }
    commit('updated',{DetailPList:result})
  },
  // 请求第二个详情页面的数据
  async getKdetail({commit,state},payload){
    // console.log(payload);
    // console.log(payload.id,payload.kid);
    let obj={};
    state.DetailPList.children.forEach((element) => {
      // console.log(element);
      // console.log(index);
      if(element.id==payload.kid){
        obj=element
      }
    });
    // console.log(obj,"-----------------------");
    commit("updated",{DetailKList:obj})
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
